using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sedna.Core.Common.Objects.Navigation;
using Sedna.Core.Controller;
using Sedna.Core.Controls.Actions.Support;

namespace Sedna.Core.Controls.Grid
{
	/// <summary>
	/// Summary description for GridEnter.
	/// </summary>
    [ValidationProperty("Text")]
	public class GridEnter: Enter, IDataGridAwareControl
	{
		private IDataGridController controller;

		public IDataGridController Controller
		{
			set { controller = value; }
		}
	    
	    

		public GridEnter(IConfiguration configuration) : base(configuration)
		{
			this.textBox.TextChanged+=new EventHandler(OnTextChanged);
		}

		private void OnTextChanged(object sender, EventArgs e)
		{
			UpdateEntity();
		}

		private void UpdateEntity()
		{
            if (this.controller.MarkedData != null)
            {
                foreach (Object o in controller.MarkedData)
                {
                    Object oo = o;
                }
            }
		    object entity = this.controller.GridSourceCache[(int)ViewState["entityIndex"]];

			if (binder.Unbind(entity, "Value")|binder.Unbind(entity, "Text"))
			{
                //Remove old value
			    //controller.TransientData.Remove(entity);
			    controller.TransientData.Add(entity);
            }

            if (this.controller.MarkedData != null)
            {
                foreach (Object o in controller.MarkedData)
                {
                    Object oo = o;
                }
            }
        }

		public void OnDataBinding(DataGridItem dataGridItem)
		{
            ViewState["entityIndex"] = dataGridItem.DataSetIndex;
			base.Bind();
			//binder.Bind(dataGridItem.DataItem, "Text");
            binder.Bind(dataGridItem.DataItem, "Text", null);
            binder.Bind("Value", Configuration.PopupButtonConfiguration.DataTranslator);
		}



		protected override void Bind() 
		{
		}

		protected override void Unbind()
		{
		}

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (controller.InvalidData != null && controller.InvalidData.Contains(this.controller.GridSourceCache[(int)ViewState["entityIndex"]]))
                this.textBox.CssClass = "invalidinput";
            base.Render(writer);
        }
	}
}
